package service

import (
	"fileNest/dao"
	"fileNest/global"
	"fileNest/model"
	"fileNest/storage"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

// 根据pathList查找所有后代节点并修改name
func UpdatePathListNameByID(targetID primitive.ObjectID, newName string) error {
	// 构建查询条件：找出所有 pathList 中包含指定 ID 的文档（即其后代节点）
	filter := bson.M{
		"path_list.id": targetID,
	}

	// 查出所有受影响的文件或文件夹
	var children []model.FileEntry
	err := dao.DBFindMoreWithOutPage("entries", filter, &children)
	if err != nil {
		return err
	}
	for _, child := range children {
		// 遍历 pathList，更新 ID 匹配的那一项的 Name
		updated := false
		for i, path := range child.PathList {
			if path.ID != nil && *path.ID == targetID {
				child.PathList[i].Name = newName
				updated = true
			}
		}

		// 如果有修改，更新到数据库中
		if updated {
			_, err := dao.UpdateOne("entries", bson.M{
				"_id": child.ID,
			}, bson.M{
				"$set": bson.M{
					"path_list": child.PathList,
				},
			})
			if err != nil {
				return err
			}
		}
	}

	return nil
}

// 定时删除任务
func Trashcleaner() {
	ticker := time.NewTicker(24 * time.Hour)
	go func() {
		for {
			// 通道阻塞 => 24 * time.Hour执行一次
			<-ticker.C
			_ = DeleteExpiredTrashFiles()
		}
	}()
}

// 删除标记文件
func DeleteExpiredTrashFiles() (err error) {
	// 筛选七天前
	threshold := time.Now().Add(-7 * 24 * time.Hour)
	var filter = bson.M{
		"is_del": true,
		"deleteAt": bson.M{
			"$lte": threshold,
		},
	}
	var result model.FileEntryList
	err = dao.DBFindMoreWithOutPage("entries", filter, &result)
	if err != nil {
		log.Println("err:", err)
		return
	}
	if err = dao.DeleteMany("entries", filter); err != nil {
		log.Println("err:", err)
		return
	}
	var StoragePathSlice []string
	for _, v := range result {
		StoragePathSlice = append(StoragePathSlice, v.StoragePath)
	}

	if err = storage.DeleteManyMinioObject(global.BucketName, StoragePathSlice); err != nil {
		log.Println("err:", err)
		return
	}
	return
}

// 递归恢复父级目录
func RestoreWithParents(id primitive.ObjectID) (err error) {
	var query = bson.M{
		"_id": id,
	}
	var result model.FileEntry
	err = dao.DBFindOne("entries", query, &result)
	if err != nil {
		return
	}
	// 递归恢复所有祖先目录
	current := result
	for current.ParentID != nil {
		var query = bson.M{
			"_id": current.ParentID,
		}
		err = dao.DBFindOne("entries", query, &current)
		if err != nil {
			break
		}
		if current.IsDel {
			dao.UpdateOne("entries", bson.M{"_id": current.ID}, bson.M{"$set": bson.M{"is_del": false, "deleteAt": nil}})
		}
	}
	return nil
}
